package org.pc2r.game.play;

import java.util.concurrent.Callable;
import java.util.logging.Logger;

import org.pc2r.game.Game;
import org.pc2r.game.GameManager;
import org.pc2r.game.model.Player;
import org.pc2r.protocole.EnumRequest;
import org.pc2r.protocole.message.DeathWinnerMessage;
import org.pc2r.protocole.message.EmptyMessage;
import org.pc2r.protocole.message.Message;

public class GameExecution implements Callable<Player> {

	private GameManager game;
	private Logger logger;
	private boolean isFinish;

	public GameExecution(Logger logger, GameManager game) {
		super();
		this.game = game;
		this.logger = logger;
	}

	@Override
	public Player call() {
		Game game2 = game.getGame();
    while (isFinish == false && game2.canContinue()) {
			Boolean call = new OneTurn(game, logger).call();
			if(call == Boolean.FALSE) {
			  return null;
			}
			// Si la partie est terminée
			if(game2.isFinished()) {
			  Player winner = game2.getLastAlivePlayer();
			  // Si tous les joueurs sont morts, on envoie un DRAWGAME, sinon un WINNER
			  Message lastMessage = (winner == null) ? new EmptyMessage(EnumRequest.DRAWGAME) : new DeathWinnerMessage(EnumRequest.AWINNERIS, winner.getName());
			  game2.broadcast(lastMessage);
			  return winner;
			}
		}
		return null;
	}
}
